package com.qq.BFMRSE.requestModule;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import com.qq.BFMRSE.entity.BloomFilter;
import com.qq.BFMRSE.entity.trapDoor;
import com.qq.BFMRSE.trapDoor.GenTropDoor;
public class searchWordModule {
	private GenTropDoor genTDTool;
	public searchWordModule(GenTropDoor genTDTool){
		this.genTDTool=genTDTool;
	}
	public String search(String url,List<String> wordList,String userName,int K)
	{
		StringBuilder searchResult=new StringBuilder();
		HttpClient httpClient=new HttpClient();
		PostMethod post=new PostMethod(url);
		trapDoor searchTrapDoor=genTDTool.getTropDoor(wordList);
		String trapString=genTDTool.getTrapJson(searchTrapDoor);
		BloomFilter trapBf=searchTrapDoor.getBf();
		String trapBitsInfo=genTDTool.getTrapBitsInfo(trapBf);
		post.setParameter("searchTrapDoor", trapString);
		post.setParameter("trapBitsInfo", trapBitsInfo);
		post.setParameter("userName", userName);
		post.setParameter("K", K+"");
		try {
			httpClient.executeMethod(post);
			int stateCode=post.getStatusCode();
			if(stateCode==200)
			{
				InputStream inStream=post.getResponseBodyAsStream();
				BufferedReader bf=new BufferedReader(new InputStreamReader(inStream));
				String temp;
				while((temp=bf.readLine())!=null)
				{
					searchResult.append(temp);
				}
			}
			else {
				System.out.println("请求失败，状态码："+stateCode);
			}
		} catch (HttpException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return searchResult.toString();
	}
}
